<?php

namespace App\Http\Middleware;

use App\Services\Admin\AdminUser;
use Closure;
use Illuminate\Support\Facades\Session;

class AdminSession
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if(empty($request->session()->get('session_id')))return redirect('/login');

        $where[] = ['id',$request->session()->get('session_id')];
        $admin = AdminUser::info($where);
        if(empty($admin))return redirect('/login');

        $user['session_id'] = $request->session()->get('session_id');
        $user['session_role_name'] = '超级管理员';

        //路由对应控制器以及方法
        $user['get_routes'] = json_decode($request->session()->get('get_routes'),1);
        //该账号有那些权限
        $user['right_list'] = json_decode($request->session()->get('right_list'),1);
        //该账号有那些大类权限
        $user['act_list'] =json_decode($request->session()->get('act_list'),1);

        $myGetRouteName = myGetRouteName();

        if(empty($user['right_list']))\Session::forget('session_id');

        if(!in_array('all', $user['right_list'])) {
            if (!empty($myGetRouteName['controller']) && !empty($myGetRouteName['method'])) {

                $bool_controle_action = "{$myGetRouteName['controller']}Controller@{$myGetRouteName['method']}";

                if (request()->ajax()) {
                    if ($myGetRouteName['controller'] != 'Index' && $myGetRouteName['method'] != 'index') {

                        if (!in_array($bool_controle_action, $user['right_list'])) {
                            die(json_encode([
                                'status' => -1,
                                'result' => [],
                                'message' => '没有权限操作！'
                            ]));
                        }
                    }
                } else {
                    if ($myGetRouteName['controller'] != 'Index' && $myGetRouteName['method'] != 'index') {

                        if (!in_array($bool_controle_action, $user['right_list'])) {
                            die('该账号没有权限操作!');
                        }

                    }
                }
            }
        }

        //导航
        $nav = $this->nav();

        View()->share('user',$user);

        View()->share('nav',$nav);

        View()->share('group',[
            'class_schedule'=>'課程表',
            'banner_list'=>'Banner',
            'store_management'=>'門店管理',
            'promotion_settings'=>'推廣設置',
            'user_management'=>'用戶管理',
            'point_program_management'=>'積分方案管理',
            'points_mall_management'=>'積分商城管理',
            'payment_management'=>'付款管理',
        ]);

        return $next($request);
    }

    //导航栏修改
    public function nav()
    {
        return $nav = config('nav');
    }
}
